package com.dajun.service;

import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.idm.api.User;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *  获取当前流程处理人
 */

@Component
public class TaskApproverService {

    @Autowired
    private TaskService taskService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private RuntimeService runtimeService;

    /**
     * 获取任务的所有潜在处理人
     */
    public List<User> getPotentialApprovers(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        
        // 1. 直接负责人
        if (task.getAssignee() != null) {
            return List.of(
                identityService.createUserQuery()
                    .userId(task.getAssignee())
                    .singleResult()
            );
        }

        // 2. 候选用户和组
        List<IdentityLink> links = taskService.getIdentityLinksForTask(taskId);
        Set<User> users = new HashSet<>();

        // 候选用户
        links.stream()
            .filter(link -> link.getUserId() != null)
            .forEach(link -> users.add(
                identityService.createUserQuery()
                    .userId(link.getUserId())
                    .singleResult()
            ));

        // 候选组中的用户
        links.stream()
            .filter(link -> link.getGroupId() != null)
            .forEach(link -> 
                users.addAll(
                    identityService.createUserQuery()
                        .memberOfGroup(link.getGroupId())
                        .list()
                )
            );

        return new ArrayList<>(users);
    }

    /**
     * 获取多实例任务的当前审批人
     */
    public String getMultiInstanceApprover(String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        return (String) taskService.getVariable(taskId, "approver");
    }
}